﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace SIGGREProto.Util
{
    class UtilInternet
    {

        public static string GetExternalIP(string Provider)
        {
            try
            {
                if ((Provider == null) || (Provider == ""))
                    Provider = "http://automation.whatismyip.com/n09230945.asp";

                HttpWebRequest WebReq = (HttpWebRequest)HttpWebRequest.Create(Provider);
                HttpWebResponse WebRes = (HttpWebResponse)WebReq.GetResponse();

                System.IO.Stream ResStream = WebRes.GetResponseStream();
                StreamReader ResStreamReader = new StreamReader(ResStream, Encoding.UTF8);

                string IP = ResStreamReader.ReadToEnd();

                ResStream.Close();
                WebRes.Close();

                return IP;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        public static string GetExternalIP()
        {
            return GetExternalIP(null);
        }

        public static string GetLocalIP()
        {
            //IPAddressMonitorSample1.Class4.DisplayDhcpServerAddresses();

            IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
            String MyIp = localIPs[localIPs.Length - 2].ToString();

            //Console.WriteLine(DreamInCode.Snippets.IpFinder.GetExternalIp2());

            IPAddress[] a = Dns.GetHostByName(Dns.GetHostName()).AddressList;
            for (int i = 0; i < a.Length; i++) ;
            //Console.WriteLine("IpAddr[{0}]={1}", i, a[i]);

            //This is a way to get any network address (not necessarily the internet ip) as pointed out in the comments:
            IPAddress host = IPAddress.None;
            foreach (IPAddress ip in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                host = ip;
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return host.ToString();
                    break;
                }
            }

            IPHostEntry host2;
            string localIP = "?";
            host2 = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host2.AddressList)
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    localIP = ip.ToString();
                }
            }
            return localIP;

            return "";


        }
    }
}
